<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Title_FormItem" prop="Title">
							<template #label>
								<WtmLabelTooltip label="招聘标题" tooltip="招聘发布的标题" />
							</template>
							<el-input v-model="searchData.Title" clearable placeholder="请输入招聘标题"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillCode_FormItem" prop="BillCode">
							<template #label>
								<WtmLabelTooltip label="单据编号" tooltip="单编号" />
							</template>
							<el-input v-model="searchData.BillCode" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="WorkflowStatus_FormItem" prop="WorkflowStatus">
							<template #label>
								<WtmLabelTooltip label="流程状态" tooltip="工作流状态" />
							</template>
							<el-select v-model="searchData.WorkflowStatus" clearable>
								<el-option key="待提交" value="待提交" label="待提交"></el-option>
								<el-option key="提交中" value="提交中" label="提交中"></el-option>
								<el-option key="审核中" value="审核中" label="审核中"></el-option>
								<el-option key="已完成" value="已完成" label="已完成"></el-option>
								<el-option key="已取消" value="已取消" label="已取消"></el-option>
								<el-option key="待处理" value="待处理" label="待处理"></el-option>
								<el-option key="处理中" value="处理中" label="处理中"></el-option>
								<el-option key="已处理" value="已处理" label="已处理"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<WtmDeptSelector v-model="searchData.GroupId" label="所属部门" :rules="[]" />
					</el-col>

					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IsExternalPublish_FormItem" prop="IsExternalPublish">
								<template #label>
									<WtmLabelTooltip label="对外发布" tooltip="是否将招聘信息发布到外网" />
								</template>
								<el-select v-model="searchData.IsExternalPublish" clearable placeholder="请选择">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ExpectedDate_FormItem" prop="ExpectedDate">
								<template #label>
									<WtmLabelTooltip label="到岗时间" tooltip="期望人员到岗的时间" />
								</template>
								<el-date-picker v-model="searchData.ExpectedDate" clearable placeholder="选择到岗时间"></el-date-picker>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="BillStatus_FormItem" prop="BillStatus">
								<template #label>
									<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
								</template>
								<el-select v-model="searchData.BillStatus" clearable>
									<el-option key="草稿" value="草稿" label="草稿"></el-option>
									<el-option key="正文" value="正文" label="正文"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Remark_FormItem" prop="Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="searchData.Remark" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysHrRecruitPublishRequestBill/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrRecruitPublishRequestBill/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysHrRecruitPublishRequestBill/UpdateExternalPublishStatusByIds'"
				icon="fa fa-bullhorn"
				type="success"
				button-text="批量发布"
				:disabled="!hasSelectedRows"
				confirm="确定要批量发布选中的招聘申请吗？"
				@click="onBatchPublish(true)"
			/>
			<WtmButton
				v-auth="'/api/SysHrRecruitPublishRequestBill/UpdateExternalPublishStatusByIds'"
				icon="fa fa-ban"
				type="warning"
				button-text="批量关闭"
				:disabled="!hasSelectedRows"
				confirm="确定要批量关闭选中的招聘申请吗？"
				@click="onBatchPublish(false)"
			/>
			<WtmButton
				v-auth="'/api/SysHrRecruitPublishRequestBill/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrRecruitPublishRequestBill/SysHrRecruitPublishRequestBillExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysHrRecruitPublishRequestBill/Edit'"
								v-if="scope.row.BillStatus === '草稿'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-if="scope.row.CanApprove == 'true'"
								:is-text="true"
								icon="-o"
								type="warning"
								button-text="审批"
								@@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-else
								v-auth="'/api/SysHrRecruitPublishRequestBill/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrRecruitPublishRequestBill/BatchDelete'"
								v-if="scope.row.BillStatus === '草稿'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="招聘发布申请;true;HengTong.Areas.Hr.Controllers;SysHrRecruitPublishRequestBill">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysHrRecruitPublishRequestBillApi as api } from '/@/views/hr/syshrrecruitpublishrequestbill/api';
import { ISysHrRecruitPublishRequestBillView, ISysHrRecruitPublishRequestBillQuery } from '/@/views/hr/syshrrecruitpublishrequestbill/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysHrRecruitPublishRequestBillQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysJobPositions: [] as ISysSelectType[],
	AllSysGroups: [] as ISysSelectType[],
	AllSysOrgs: [] as ISysSelectType[],
	AllSysHrRecruitPools: [] as ISysSelectType[],
});

const searchData = ref<ISysHrRecruitPublishRequestBillQuery>({
	Title: null,
	Description: null,
	HireNumber: null,
	ExpectedDate: null,
	JobRequirement: null,
	EducationRequirement: null,
	MajorRequirement: null,
	GenderRequirement: null,
	AgeRequirement: null,
	OtherRequirement: null,
	SalaryRange: null,
	Benefits: null,
	JobPositionId: null,
	PublishStartDate: null,
	PublishEndDate: null,
	IsExternalPublish: null,
	ContactPerson: null,
	ContactPhone: null,
	ContactEmail: null,
	RecruitPoolId: null,
	Approver: null,
	ApprovalTime: null,
	GroupId: null,
	OrgId: null,
	BillCode: null,
	BillStatus: null,
	WorkflowStatus: null,
	Remark: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		// === 核心业务字段（最高优先级） ===
		{ title: '招聘发布单号', key: 'BillCode', type: 'text', isCheck: true },
		{ title: '招聘标题', key: 'Title', type: 'text', isCheck: true },
		{ title: '招聘人数', key: 'HireNumber', type: 'text', isCheck: true },
		{ title: '公司', key: 'OrgName', type: 'text', isCheck: true },
		{ title: '所属部门', key: 'GroupName', type: 'text', isCheck: true },
		// === 状态字段（高优先级） ===
		{
			title: '流程状态',
			key: 'WorkflowStatus',
			type: 'tag',
			isCheck: true,
			tagType: (row: ISysHrRecruitPublishRequestBillView) => {
				const statusMap: Record<string, string> = {
					待提交: 'info',
					提交中: 'info',
					审核中: 'warning',
					已完成: 'success',
					已取消: 'danger',
				};
				return statusMap[row.WorkflowStatus || ''] || 'info';
			},
		},
		{
			title: '单据状态',
			key: 'BillStatus',
			type: 'tag',
			isCheck: true,
			tagType: (row: ISysHrRecruitPublishRequestBillView) => {
				const statusMap: Record<string, string> = {
					草稿: 'info',
					正文: 'warning',
				};
				return statusMap[row.BillStatus || ''] || 'info';
			},
		},

		// === 时间相关字段（中等优先级） ===
		{ title: '到岗时间', key: 'ExpectedDate', type: 'text', isCheck: true },
		{ title: '发布开始时间', key: 'PublishStartDate', type: 'text', isCheck: true },
		{ title: '发布结束时间', key: 'PublishEndDate', type: 'text', isCheck: true },

		{ title: '审批人', key: 'Approver', type: 'text', isCheck: true },
		{ title: '审批时间', key: 'ApprovalTime', type: 'text', isCheck: true },

		// === 招聘要求字段（中等优先级） ===
		{ title: '学历要求', key: 'EducationRequirement', type: 'text', isCheck: true },
		{ title: '薪资范围', key: 'SalaryRange', type: 'text', isCheck: true },
		{ title: '专业要求', key: 'MajorRequirement', type: 'text', isCheck: true },

		// === 联系方式字段（中低优先级） ===
		{ title: '联系人', key: 'ContactPerson', type: 'text', isCheck: true },
		{ title: '联系电话', key: 'ContactPhone', type: 'text', isCheck: true },
		{ title: '联系邮箱', key: 'ContactEmail', type: 'text', isCheck: true },

		// === 发布设置字段（中低优先级） ===
		{ title: '是否对外发布', key: 'IsExternalPublish', type: 'switch', isCheck: true },
		{ title: '招聘需求池', key: 'RecruitPoolsName', type: 'text', isCheck: true },

		// === 详细描述字段（低优先级） ===
		{ title: '招聘描述', key: 'Description', type: 'text', isCheck: true },
		{ title: '岗位要求', key: 'JobRequirement', type: 'text', isCheck: true },
		{ title: '福利待遇', key: 'Benefits', type: 'text', isCheck: true },
		{ title: '性别要求', key: 'GenderRequirement', type: 'text', isCheck: true },
		{ title: '年龄要求', key: 'AgeRequirement', type: 'text', isCheck: true },
		{ title: '其他要求', key: 'OtherRequirement', type: 'text', isCheck: true },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysHrRecruitPublishRequestBillView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysHrRecruitPublishRequestBillView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysHrRecruitPublishRequestBillView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrRecruitPublishRequestBillView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};

// 批量发布
const onBatchPublish = async (IsExternalPublish: boolean) => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrRecruitPublishRequestBillView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			loading.value = true;
			const response = await api().updatePublishStatusByIds({ ids: selectedIds, IsExternalPublish: IsExternalPublish });
			if (response.Code == 200) {
				// 先清除选择状态
				tableRef.value?.clearSelection();
				// 再重新获取数据
				getTableData();
				ElMessage.success(IsExternalPublish ? '批量发布成功' : '批量关闭成功');
			} else {
				ElMessage.error(response.Message || '批量发布失败');
			}
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		} finally {
			loading.value = false;
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysHrRecruitPublishRequestBill/GetSysJobPositions', [], false).then((x) => (stateData.AllSysJobPositions = x)),
		other.getSelectList('/api/SysHrRecruitPublishRequestBill/GetSysGroups', [], false).then((x) => (stateData.AllSysGroups = x)),
		other.getSelectList('/api/SysHrRecruitPublishRequestBill/GetSysOrgs', [], false).then((x) => (stateData.AllSysOrgs = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
